package com.ccteam.fluidmusic.ui.playlist

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ConcatAdapter
import com.ccteam.fluidmusic.*
import com.ccteam.fluidmusic.databinding.FragmentPlaylistSheetDetailBinding
import com.ccteam.fluidmusic.utils.EventObserver
import com.ccteam.fluidmusic.utils.TransitionUtils
import com.ccteam.fluidmusic.utils.generateContainerTransform
import com.ccteam.fluidmusic.ui.moment.AddMomentActivity
import com.ccteam.fluidmusic.view.adapters.*
import com.ccteam.fluidmusic.view.base.LightBounceEdgeEffectFactory
import com.ccteam.fluidmusic.view.bean.*
import com.ccteam.fluidmusic.widget.AnimToolbarScrollListener
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment.Companion.RESULT_PLAYLIST_TYPE_KEY
import com.ccteam.fluidmusic.view.fragments.common.DescriptionData
import com.ccteam.fluidmusic.ui.dialog.MusicMoreBottomSheetFragment.Companion.RESULT_PLAYLIST_MUSIC_DELETE
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import com.ccteam.fluidmusic.widget.SNACKBAR_BOTTOM
import com.ccteam.fluidmusic.widget.snackbar
import com.ccteam.model.moment.MOMENT_SHARE_TYPE_PLAYLIST
import com.ccteam.shared.result.moment.MomentListItem
import com.ccteam.shared.result.playlistsheet.PlaylistSheetDetailHeaderItem
import com.ccteam.shared.result.playlistsheet.PlaylistSheetMusicItem
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.orhanobut.logger.Logger
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/16
 *
 * 歌单详情页面
 */
@AndroidEntryPoint
class PlaylistSheetDetailFragment: Fragment() {

    private var _binding: FragmentPlaylistSheetDetailBinding? = null
    private val binding: FragmentPlaylistSheetDetailBinding get() = _binding!!

    private val playlistSheetDetailViewModel by viewModels<PlaylistSheetDetailViewModel>()

    private val mainActivityViewModel by activityViewModels<MainActivityViewModel>()

    @Inject lateinit var lightBounceEdgeEffectFactory: LightBounceEdgeEffectFactory

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setFragmentResultListener(RESULT_PLAYLIST_TYPE_KEY){ _, bundle ->
            if(bundle.getBoolean(RESULT_PLAYLIST_TYPE_KEY)){
                Logger.d("歌单信息更新，需要刷新")
                playlistSheetDetailViewModel.refreshPlaylistDetail()
            }
        }

        setFragmentResultListener(RESULT_PLAYLIST_MUSIC_DELETE){ _, bundle ->
            val mediaInfo = bundle.getParcelable<MoreInfoData>(RESULT_PLAYLIST_MUSIC_DELETE)
            if(mediaInfo != null){
                // 删除歌单
                MaterialAlertDialogBuilder(requireContext())
                    .setTitle(R.string.description_delete_playlistSheet_info)
                    .setMessage(getString(R.string.description_delete_music_playlistSheet,mediaInfo.mediaTitle))
                    .setNegativeButton(R.string.description_cancel) { _,_ -> }
                    .setPositiveButton(R.string.description_delete) { _,_ ->
                        playlistSheetDetailViewModel.deletePlaylistSheetMusic(mediaInfo)
                    }.show()
            }
        }

        exitTransition = TransitionUtils.exitScale
        reenterTransition = TransitionUtils.enterScale
        // 设置共享动画
        sharedElementEnterTransition = generateContainerTransform(requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentPlaylistSheetDetailBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        val headerAdapter = PlaylistSheetDetailHeaderAdapter(headerClickedCallback)
        val dataAdapter = PlaylistSheetDetailMusicAdapter(
            musicClickedCallback
        )

        binding.toolbarPlaylistList.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        binding.rvPlaylistSheetDetail.adapter = ConcatAdapter(headerAdapter,dataAdapter)

        // 设置回弹效果
        lightBounceEdgeEffectFactory.applyBounceView(binding.rvPlaylistSheetDetail,this)
        binding.rvPlaylistSheetDetail.edgeEffectFactory = lightBounceEdgeEffectFactory
        binding.rvPlaylistSheetDetail.addOnScrollListener(AnimToolbarScrollListener(binding.toolbarTitle))

        playlistSheetDetailViewModel.loadMessage.observe(viewLifecycleOwner, {
            binding.statusView.changeToErrorStatus(it)
            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
        })

        playlistSheetDetailViewModel.shouldShowShareButton.observe(viewLifecycleOwner, {
            binding.toolbarPlaylistList.menu.findItem(R.id.toolbar_share).isVisible = it
        })

        playlistSheetDetailViewModel.deletePlaylistLoadMessage.observe(viewLifecycleOwner, EventObserver{
            if(it is LoadMessage.Success){
                view.snackbar(R.string.description_delete_playlistSheet_success).show()
                findNavController().navigateUp()
            } else if(it is LoadMessage.Error){
                view.snackbar(it.errorMessage.description.toString()).show()
            }
        })

        playlistSheetDetailViewModel.deleteMusicLoadMessage.observe(viewLifecycleOwner, EventObserver {
            if(it is LoadMessage.Success){
                view.snackbar(R.string.description_delete_playlistSheet_music_success).show()
                playlistSheetDetailViewModel.refreshPlaylistDetail()
            } else if(it is LoadMessage.Error){
                view.snackbar(it.errorMessage.description.toString()).show()
            }
        })


        playlistSheetDetailViewModel.playlistSheetHeader.observe(viewLifecycleOwner, {
            if(!it.isNullOrEmpty()){
                binding.toolbarTitle.text = it[0].playlistSheetTitle
                headerAdapter.submitList(it)
            }
        })

        playlistSheetDetailViewModel.playlistSheetMusicList.observe(viewLifecycleOwner, {
            dataAdapter.submitList(it)
        })

        binding.statusView.setRetryClickListener {
            playlistSheetDetailViewModel.refreshPlaylistDetail()
        }

        binding.toolbarPlaylistList.setOnMenuItemClickListener { menuItem ->
            return@setOnMenuItemClickListener when(menuItem.itemId){
                R.id.toolbar_share ->{
                    val playlistInfo = playlistSheetDetailViewModel.playlistSheetHeader.value!![0]
                    startActivity(Intent(requireContext(), AddMomentActivity::class.java).apply {
                        putExtra("shareContent", MomentListItem.MomentShareItem(
                            playlistInfo.id,
                            MOMENT_SHARE_TYPE_PLAYLIST,playlistInfo.playlistSheetTitle,"",playlistInfo.userPhotoUrl
                        ))
                    })
                    true
                }
                else ->
                    false
            }
        }
    }

    private val headerClickedCallback = object: PlaylistSheetDetailHeaderCallback{

        // 当点击添加歌曲到播放列表时
        override fun addMusicToPlaylistClicked(item: PlaylistSheetDetailHeaderItem) {
            findNavController().navigate(NavAddMediaDirections
                .actionGlobalAddOnlineMediaFragment(AddOnlineMediaFragment.TYPE_ADD_MUSIC_PLAYLIST,item))
        }

        // 当点击编辑播放列表时
        override fun editPlaylistClicked(item: PlaylistSheetDetailHeaderItem) {
            findNavController().navigate(
                PlaylistSheetDetailFragmentDirections.actionPlaylistSheetDetailFragmentToPlaylistSheetEditFragment(
                    PlaylistSheetEditInfo(
                        item.id,
                        item.playlistSheetTitle,
                        item.playlistSheetImgUrl,
                        item.introduction
                    )
                )
            )
        }

        // 当点击删除播放列表时
        override fun deletePlaylistClicked(item: PlaylistSheetDetailHeaderItem) {
            // 删除歌单
            MaterialAlertDialogBuilder(requireContext())
                .setTitle(R.string.description_delete_playlistSheet_info)
                .setMessage(getString(R.string.description_delete_playlistSheet,item.playlistSheetTitle))
                .setNegativeButton(R.string.description_cancel) { _,_ -> }
                .setPositiveButton(R.string.description_delete) { _,_ ->
                    playlistSheetDetailViewModel.deletePlaylistSheet()
                }.show()
        }

        // 当点击播放时
        override fun playClicked() {
            playlistSheetDetailViewModel.playlistSheetMusicList.value?.let { musics ->
                if(!musics.isNullOrEmpty()){
                    Logger.d("播放:${musics[0].title}")
                    mainActivityViewModel.playMediaId(
                        musics[0].mediaId,playlistSheetDetailViewModel.parentId,true
                    )
                }
            }
        }

        // 当点击随机播放时
        override fun shufflePlayClicked() {
            playlistSheetDetailViewModel.playlistSheetMusicList.value?.let { musics ->
                if(!musics.isNullOrEmpty()){
                    Logger.d("播放:${musics[0].title}")
                    mainActivityViewModel.playMediaId(
                        musics[(musics.indices).random()].mediaId,playlistSheetDetailViewModel.parentId,false,true
                    )
                }
            }
        }

        override fun descriptionClicked(item: PlaylistSheetDetailHeaderItem) {
            findNavController().navigate(NavDescriptionDirections.actionGlobalDescriptionDialog(
                DescriptionData(item.playlistSheetTitle,item.introduction)
            ))
        }

    }

    private val musicClickedCallback = object: PlaylistSheetMusicItemClickCallback {

        override fun musicItemClicked(item: PlaylistSheetMusicItem) {
            mainActivityViewModel.playMediaId(item.mediaId,playlistSheetDetailViewModel.parentId,true)
        }

        override fun moreClicked(item: PlaylistSheetMusicItem) {
            playlistSheetDetailViewModel.parentId?.let { parentId ->
                findNavController().navigate(NavMoreMusicDirections.actionGlobalMusicMoreBottomSheetFragment(
                    MoreInfoData(parentId,item.mediaId,item.title,item.subtitle,false,item.albumId,
                        item.artistInfo,item.albumArtUri,item.isSelfUserMusic,item.id,
                        canShare = playlistSheetDetailViewModel.isLogin.value == true)
                ))
            }
        }


    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}